﻿using CefSharp;
using CefSharpWinformDemo;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Utils;

namespace CefSharpWinformDemo
{
    public class CefLifeSpanHandler : CefSharp.ILifeSpanHandler
    {
        public CefLifeSpanHandler()
        {

        }

        public bool DoClose(IWebBrowser browserControl, CefSharp.IBrowser browser)
        {
            if (browser.IsDisposed || browser.IsPopup)
            {
                return false;
            }

            return true;
        }

        public void OnAfterCreated(IWebBrowser browserControl, IBrowser browser)
        {

        }

        public void OnBeforeClose(IWebBrowser browserControl, IBrowser browser)
        {
        }

        public bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
        {
            var chromiumWebBrowser = (ExtChromiumBrowser)browserControl;
            BrowserPopupWin win = null;

            var needPostData = false;
            if (targetUrl.Contains("file:///")) needPostData = true;
            if (targetUrl.Contains("http://localhost")) needPostData = true;

            chromiumWebBrowser.Invoke(new Action(() =>
            {
                if (needPostData)
                {
                    win = new BrowserPopupWin();
                    win.ShowInTaskbar = false;
                    win.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
                    win.Left = -10000;
                    win.Top = -10000;
                    win.Height = 0;
                    win.Width = 0;
                    win.Show();

                    IntPtr handle = win.Handle;
                    windowInfo.SetAsChild(handle);
                }

                NewWindowEventArgs e = new NewWindowEventArgs(targetUrl);

                chromiumWebBrowser.OnNewWindow(e);

                if (needPostData)
                {
                    //等待PostData有数据，并解决post提交跳转到结果页面，在结果页面再次post提交到另一个页面
                    e.NewBrowser.FrameLoadEnd += (ss, ee) =>
                    {
                        if (chromiumWebBrowser.PostData != null)
                        {
                            IRequest request = frame.CreateRequest();
                            request.Url = targetUrl;
                            request.Method = "POST";

                            request.InitializePostData();
                            var element = request.PostData.CreatePostDataElement();
                            element.Bytes = chromiumWebBrowser.PostData;
                            request.PostData.AddElement(element);
                            chromiumWebBrowser.PostData = null;
                            e.NewBrowser.GetMainFrame().LoadRequest(request);
                        }
                    };
                }

                e.NewBrowser.Load(targetUrl);

                chromiumWebBrowser.Invoke(new Action(() =>
                {
                    if (win != null) win.Close();
                }));
            }));

            newBrowser = null;
            if (win != null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

    }
}
